﻿using System.IO;
using System.Windows.Forms;
using Xmef.Interfaces;
using Xmef.Library;
using Xmef.Serializer;
using System.Diagnostics;

namespace XmlDataReader
{
    public partial class ComplexDataSerializationForm : Form
    {
        private IXmlFileStreamSerializer<DataV3> _serializer = new XmlFileSerializer<DataV3>();

        public ComplexDataSerializationForm()
        {
            InitializeComponent();
        }

        public void ReadXml(string fileName)
        {
            propertyGrid1.SelectedObject = null;
            if (_serializer.Attach(fileName))
            {
                if (_serializer.Deserialize(DataV3.Formatter))
                {
                    _serializer.Detach(fileName);
                    propertyGrid1.SelectedObject = _serializer.RuntimeObject;
                }
                _serializer.Detach(fileName);
            }
        }
        public void WriteXml(string fileName)
        {
            textBox1.Clear();
            if (_serializer.Attach(fileName))
            {
                if (_serializer.Serialize(_serializer.RuntimeObject, DataV3.Formatter))
                {
                    _serializer.Detach(fileName);
                    textBox1.Text = File.ReadAllText(fileName);
                }
                _serializer.Detach(fileName);
            }
        }

        private void toolStripButton1_Click(object sender, System.EventArgs e)
        {
            LogHelper.Write(">>> read");
            ReadXml("puzzle.sudoku");
            LogHelper.Write("<<< read");
            LogHelper.Write(">>> write");
            WriteXml("puzzle.sudoku");
            LogHelper.Write("<<< write");
        }

        private void ComplexDataSerializationForm_Load(object sender, System.EventArgs e)
        {
            LogHelper.WriteSync(">>> online");
        }

        private void ComplexDataSerializationForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            LogHelper.WriteSync("<<< offline");
        }
    }
}
